package org.renhj.loadbalance.impl;

import org.renhj.consumer.RpcClient;
import org.renhj.loadbalance.AbstractLoadBalance;
import org.renhj.metric.Metric;
import org.renhj.metric.ZookeeperMetric;

import java.util.*;
import java.util.stream.Collectors;

public class MiniCostLoadBalance extends AbstractLoadBalance {

    @Override
    public RpcClient doSelect(List<RpcClient> clients) throws Exception {
        List<Metric> metrics = new ArrayList<>(ZookeeperMetric.getInstance().getMetrics().values());
        if (metrics.isEmpty()) {
            // 如果没有监控数据，随机一个
            return random(clients);
        } else {
            // 如果有监控数据，则从监控数据中获取响应时间最小的一个客户端
            return min(clients);
        }
    }

    public RpcClient random(List<RpcClient> clients) {
        int length = clients.size();
        return clients.get(new Random().nextInt(length));
    }
    public RpcClient min(List<RpcClient> clients) throws Exception {
        List<Metric> metrics = new ArrayList<>(ZookeeperMetric.getInstance().getMetrics().values());
        Collections.sort(metrics);
        List<Metric> minMetrics = new ArrayList<>();
        minMetrics.add(metrics.get(0));
        for (int i = 1; i < metrics.size(); i++) {
            if (metrics.get(i).getCost().equals(metrics.get(0).getCost())) {
                minMetrics.add(metrics.get(i));
            }
        }
        int size = minMetrics.size();
        String address = minMetrics.get(new Random().nextInt(size)).getAddress();
        return clients.stream().filter(client -> (client.getHost() + ":" + client.getPort()).equals(address)).collect(Collectors.toList()).get(0);
    }

}
